<template>
  <div>
    <home-head />
    <div class="wrap">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <!-- 轮播 -->
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="banner in banners" :key="banner.id">
            <img :src="banner.picUrl" alt />
          </van-swipe-item>
        </van-swipe>
        <!-- /轮播 -->
        <!-- 宫格导航 -->
        <van-grid class="cate" column-num="3" clickable>
          <van-grid-item
            v-for="cate in cates"
            :key="cate.id"
            :icon="cate.icon"
            :to="{
              path: '/itemLists',
              query: {
                cateId: cate.id
              }
            }"
            :text="cate.name" />
        </van-grid>
        <!-- /宫格导航 -->
        <!-- 推荐商品 -->
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="我也是有底线了"
          :offset="50"
          @load="onLoad"
        >
        <home-items
          @clickItem="enterDetail"
          @addCart="addCart"
          :items="items" />
        </van-list>
        <!-- /推荐商品 -->
      </van-pull-refresh>
    </div>
    <tabbar />
  </div>
</template>

<script>
import { fetchCates, fetchHomeBanner, fetchItems, addCart } from '@api'
import Tabbar from '../../components/Tabbar.vue'
import HomeHead from './components/HomeHead.vue'
import HomeItems from './components/HomeItems.vue'
import { isLogin } from '@utils'
import { Toast } from 'vant'
export default {
  name: 'home',
  data () {
    return {
      cates: [],
      banners: [],
      items: [],
      // 下拉刷新 loading状态
      isLoading: false,
      page: 1, // 商品请求哪一页
      pageSize: 5, // 一页多少条
      loading: false, // 是否上拉 触底
      finished: false // 是否上拉 到达最后一页
    }
  },
  created () {
    this.fetchCates()
    this.fetchBanners()
  },
  methods: {
    addCart (id) {
      /*
      判断用户是否登录
      登录 则 加入购物车
      否则：弹出提示 并跳转到登录页
      */
      if (isLogin()) {
      //  登录了
        addCart({
          goodsId: id,
          number: 1,
          token: localStorage.getItem('token') || ''
        }).then(res => {
          if (res.data.code === 0) {
            this.$store.commit('cart/init_cart_info', {
              items: res.data.data.items,
              total: res.data.data.price
            })
            Toast({
              type: 'success',
              duration: 1000,
              message: '加入成功'
            })
          }
        })
      } else {
      //  没有登录
        Toast({
          message: '请先登录',
          duration: 1000,
          onClose: () => {
            // 跳转到登录页
            this.$router.push({
              path: '/login',
              query: {
                from: '/home'
              }
            })
          }
        })
      }
    },
    enterDetail (id) {
      this.$router.push(`/detail/${id}`)
    },
    onLoad () {
      console.log('触底了')
      // 上拉触底的事件
      this.fetchItems()
      // 请求下一页数据
      this.page++
    },
    onRefresh () {
      // 用户下拉 监听函数
      this.fetchItems()
      // 上拉加载 请求page 回到1
      this.page = 1
      this.items = []
      this.finished = false
    },
    fetchItems () {
      fetchItems({
        categoryId: 72399,
        page: this.page,
        pageSize: this.pageSize
      }).then((res) => {
        // 结束下拉刷新的loading状态
        this.isLoading = false
        // 要在 数据成功获取后 将触底状态变成false
        this.loading = false
        if (res.data.code === 700) {
          // 到了最后一页了
          this.finished = true
        }
        if (res.data.code === 0) {
          this.items = [...this.items, ...res.data.data.result]
        }
      })
    },
    fetchCates () {
      // 获取分类数据
      fetchCates().then((res) => {
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    },
    fetchBanners () {
      // 获取首页轮播
      fetchHomeBanner().then((res) => {
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    }
  },
  components: {
    Tabbar,
    HomeHead,
    HomeItems
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding: 50px 0;
  .my-swipe {
    img {
      width: 100%;
    }
  }
}
</style>
